<template>
<div>
  <div class="screening2-listdetail" v-if="screeningList.length">
    <div class="one">
      <span>{{detailInfo.id}}</span>
      <span>{{detailInfo.time.split(' ').pop()}}</span>
    </div>
    <div class="two" @click="showImage(detailInfo.image)">
      <img :src="detailInfo.image" alt="">
      <p>{{detailInfo.mode==0?'左眼':'右眼'}}</p>
    </div>
    <div class="three">
      <span>姓名:<em>{{detailInfo.name}}</em></span>
      <span>年龄:<em>{{detailInfo.age}}</em></span>
      <span>电话:<em>{{detailInfo.telephone}}</em></span>
      <span>家族病史:<em>{{detailInfo.medical_history}}</em></span>
    </div>
    <div class="three">
      <span>病历号:<em>{{detailInfo.medical_num}}</em></span>
      <span>模式:<em>{{detailInfo.mode==0?'左眼':'右眼'}}</em></span>
      <span class="status">状态:
                    <em v-if="detailInfo.status == 0" style="color:rgb(234, 0, 64);">待开始</em>
                    <em v-if="detailInfo.status == 2" style="color:rgb(213, 168, 0);">筛查中</em>
                    <em v-if="detailInfo.status == 1" style="color:rgb(79, 199, 130);">已完成</em>
                </span>
      <span class="mode">操作:<em class="start" @click="start(detailInfo)"
                                          v-if="detailInfo.status==0">开始</em><em
                        v-if="detailInfo.status==0">|</em><em
                        class="detail" @click="getDetail(detailInfo)" v-if="detailInfo.status==1">详情</em><em
                        v-if="detailInfo.status==1">|</em><em
                        class="delete" @click="deleteItem(detailInfo)">删除</em></span>
    </div>
    <div class="three">
      <span>初步检测结果:<em class="result">{{detailInfo.result}}</em></span>
    </div>
  </div>
  <div class="screening2-autoupload">
    <!--<input type="text" style="background-color: red">-->
    <button class="image-upload">
                <span>批量眼底筛查</span>
                <form><input type="file" multiple @change="onFileChange" accept="image/*"></form>
            </button>
    <span class="auto-screen">自动筛查<i-switch v-model="auto_screen" @on-change="autoScreen"/></span>
  </div>
  <div class="screening2-container" ref="screening_container" :style="{maxHeight:clientHeight + 'px',width:clientWidth + 'px' }" v-if="screeningList.length">
    <div>
      <p class="screening2-item">
        <span class="one"></span>
        <span class="one">用户</span>
        <span class="one">图像</span>
        <span class="two">病历号</span>
        <span class="one">模式</span>
        <span class="one">状态</span>
        <span class="two">操作</span>
      </p>
      <div class="screening2-list" v-for="(item,index) in screeningList" @click="showDetail(item)" v-if="updateList">
        <div class="left">
          <span>{{item.id}}</span>
          <span>{{item.time.split(' ').pop()}}</span>
        </div>
        <div class="right">
          <span class="one update-info" @click="updateInfo(item)">{{item.name}}</span>
          <!--<span class="one" @click.stop="showImage(item.image)"><img :src="item.image" alt=""></span>-->
          <span class="one" @click="showImage(item.image)"><img :src="item.image" alt=""></span>
          <span class="two"><input type="text" maxlength="20" placeholder="在此输入病历号"
                                                 v-model="item.medical_num"
                                                 :ref="'input'+index" :key="index"
                                                 @blur="updateMedicalNum(item.medical_num,item.image_id)"
                                                 @focus="getMedicalNum(item.medical_num,index)"></span>
          <span class="one change-mode" @click="changeMode(item)">{{item.mode==0?'左眼':'右眼'}}</span>
          <span class="one start" v-if="item.status==0">待开始</span>
          <span class="one screening" v-if="item.status==2">筛查中</span>
          <span class="one finish" v-if="item.status==1">已完成</span>
          <span class="two"><em @click="start(item)" v-if="item.status==0" class="start-red">开始</em><em
                                v-if="item.status==0">|</em><em
                                @click="getDetail(item)" v-if="item.status==1" class="start-red">详情</em><em
                                v-if="item.status==1">|</em><em @click="deleteItem(item)">删除</em></span>
        </div>
      </div>
    </div>
  </div>
  <Modal v-model="visible">
    <img :src="showImgUrl" v-if="visible" alt="" style="width: 100%;">
  </Modal>
  <Modal v-model="modal1" title="信息录入" class-name="screening2-infoform" ok-text="保存" @on-ok="confirm" @on-cancel="cancel">
    <div class="screening2-info">
      <p>
        <span><em>*</em>身份证号：<input type="number" v-model="userDetailInfo.identify_num"
                                    v-on:input="limitNum(0,userDetailInfo.identify_num)"></span>
        <span><em>*</em>姓&emsp;&emsp;名：<input type="text" v-model="userDetailInfo.name"></span>
      </p>
      <p>
        <!--<span><em>*</em>性&emsp;&emsp;别：-->
        <span>性&emsp;&emsp;别：
              <Select v-model="userDetailInfo.gender" style="width: auto;display: block">
                <Option v-for="item in genderList" :value="item.label" :key="item.value">{{item.label}}</Option>
              </Select>
            </span>
        <span>
              <!--<em>*</em>出生日期：-->
              出生日期：
              <DatePicker type="date" placeholder="请选择" :value="userDetailInfo.birth_date"
                          @on-change="getDate(userDetailInfo,$event)"
                          format="yyyy-MM-dd" style="width: 100%;"></DatePicker>
            </span>
      </p>
      <p>
        <!--<span><em>*</em>手&nbsp;&nbsp;机&nbsp;&nbsp;号：<input type="text" v-model="userDetailInfo.telephone"-->
        <span>手&nbsp;&nbsp;机&nbsp;&nbsp;号：<input type="text" v-model="userDetailInfo.telephone"
                                                             v-on:input="limitNum(1,userDetailInfo.telephone)"></span>
        <span>
              <!--<em>*</em>籍&emsp;&emsp;贯：<Cascader :data="nativePlace" v-model="userDetailInfo.birth_place" filterable-->
              籍&emsp;&emsp;贯：<Cascader :data="nativePlace" v-model="userDetailInfo.birth_place" filterable
                                       style="width: 100%;display: inline-block"></Cascader>
            </span>
      </p>
      <p>
        <span>家族病史：<input type="text" v-model="userDetailInfo.medical_history"></span>
      </p>
    </div>
    <div slot="footer">
      <Button type="text" size="large" @click="modal1=false">取消</Button>
      <Button type="primary" size="large" @click="confirm">确定</Button>
    </div>
  </Modal>
  <!--<Modal width="20" v-model="deleteModal" @on-ok="deleteList">-->
  <!--<p style="font-size: 20px;margin: 20px 0;">确定删除？</p>-->
  <!--</Modal>-->
</div>
</template>

<script>
const ipcRender = require('electron').ipcRenderer;
import axios from 'axios';
import {
  BackURL
} from "../js/config";
import {
  FrontURL
} from "../js/config";
import BScroll from 'better-scroll';
import event from '../components/event';

export default {
  name: "screening2",
  data() {
    return {
      screeningList: [
        // {
        //     number: '03',
        //     time: '16:07:47',
        //     name: '未命名4',
        //     image: require('../assets/logo.png'),
        //     mode: 0,
        //     status: 0,
        //     medical_num: 'U0001201810150001'
        // },
        // {
        //     number: '04',
        //     time: '16:07:47',
        //     name: '未命名4',
        //     image: require('../assets/logo.png'),
        //     mode: 1,
        //     status: 2,
        //     medical_num: 'U0001201810150002'
        // }
      ],
      visible: false,
      showImgUrl: '',
      screening_scroll: '',
      scrollY: 0,
      clientHeight: 0,
      clientWidth: 0,
      detailInfo: {
        number: '',
        time: '',
        name: '',
        image: '',
        mode: 0,
        status: 0,
        age: 0,
        telephone: 0,
        medical_history: '',
        id: 0,
        result: ''
      },
      auto_screen: false,
      oldMedicalNum: '',
      modal1: false,


      name: '',
      gender: '',
      birthDate: '',
      birth_place: [],
      cardNum: '',
      telephone: '',
      age: '',
      genderList: [{
          value: 0,
          label: '男'
        },
        {
          value: 1,
          label: '女'
        }
      ],
      nativePlace: [],
      dateValue: '',
      history: '',
      userDetailInfo: {},
      waitingScreeningList: [],
      finishScreeningList: 0,
      underScreeningList: 0,
      deleteModal: true,
      patientInfo: {},
      // refreshComponent: true,
      updateList: true
    }
  },
  methods: {
    debounce(func, delay) {
      let timer;
      return function(...args) {
        if (timer) {
          clearTimeout(timer)
        }
        timer = setTimeout(() => {
          func.apply(this, args)
        }, delay)
      }
    },
    deleteList() {
      console.log('delete');
    },
    limitNum(num, item) {
      if (num == 0) {
        if (this.userDetailInfo.identify_num.length > 18) {
          this.userDetailInfo.identify_num = item.slice(0, 18);
          return;
        }
      }
      if (num == 1) {
        if (this.userDetailInfo.telephone.length > 11) {
          this.userDetailInfo.telephone = item.slice(0, 11);
          return;
        }
      }
    },
    deleteItem(obj) {
      console.log(obj);
      if (obj.status == 2) {
        return;
      } else if (obj.status == 0) {
        this.screeningList.forEach((item, index) => {
          if (this.screeningList[index].id == obj.id) {
            this.screeningList.splice(index, 1);
            window.sessionStorage.setItem('screeningList', JSON.stringify(this.screeningList));
          }
        })
        this.waitingScreeningList.forEach((item, index) => {
          if (this.waitingScreeningList[index].id == obj.id) {
            this.waitingScreeningList.splice(index, 1);
            window.localStorage.setItem('waitingScreeningList', JSON.stringify(this.waitingScreeningList))
          }
        })
        axios.delete(BackURL + 'tasks', {
          data: obj
        }).then((res) => {
          console.log('delete res', res)
        }).catch((err) => {
          console.log('delete err', err);
        })
      } else {
        this.screeningList.forEach((item, index) => {
          if (this.screeningList[index].id == obj.id) {
            this.screeningList.splice(index, 1);
            window.sessionStorage.setItem('screeningList', JSON.stringify(this.screeningList));
          }
        })
      }
    },
    getDate(obj, e) {
      // console.log('getObj', obj);
      console.log('getDate', e);
      this.birthDate = e
      obj.birth_date = e;
    },
    updateInfo(item) {
      console.log('this.userDetailInfo', item);
      this.userDetailInfo = item;
      this.modal1 = true;
    },
    cancel() {
      console.log('cancel');
    },
    codeNumberVerify(num) {
      var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      if (reg.test(num) === false) {
        // alert("身份证输入不合法");
        return false;
      } else {
        return true;
      }
    },
    telephoneVerify(num) {
      var reg = /^1(3|4|5|7|8)\d{9}$/;
      if (reg.test(num) === false) {
        return false;
      } else {
        return true;
      }
    },
    computeAge(time) {
      var year = new Date().getFullYear();
      var month = new Date().getMonth() + 1;
      var date = new Date().getDate();
      var birth = time.split('-');
      var age = year - birth[0];
      if (month > birth[1]) {
        return age;
      } else if (month < birth[1]) {
        return age - 1;
      } else {
        if (date >= birth[2]) {
          return age;
        } else {
          return age;
        }
      }
    },
    confirm() {
      console.log('confirm');
      if (this.userDetailInfo.birth_date) {
        this.userDetailInfo.age = this.computeAge(this.userDetailInfo.birth_date);
      }
      //身份证号验证
      if (!this.userDetailInfo.identify_num) {
        this.$Message.info({
          content: '请输入身份证号'
        });
        return;
      }
      if (this.userDetailInfo.identify_num && !this.codeNumberVerify(this.userDetailInfo.identify_num)) {
        this.$Message.info({
          content: '请输入正确的身份证号'
        });
        return;
      }
      //电话号码验证
      if (!this.userDetailInfo.name) {
        this.$Message.info({
          content: '请输入姓名'
        });
        return;
      }
      if (this.userDetailInfo.telephone && !this.telephoneVerify(this.userDetailInfo.telephone)) {
        this.$Message.info({
          content: '请输入正确的电话号码'
        });
        return;
      }

      // if (!this.userDetailInfo.name || !this.userDetailInfo.telephone || !this.userDetailInfo.gender || !this.userDetailInfo.birth_date || !this.userDetailInfo.identify_num || this.userDetailInfo.birth_place.length == 0) {
      //     this.$Message.info({content: '请完善基本信息'});
      //     return;
      // }
      var data = {};
      for (var i in this.userDetailInfo) {
        if (i == 'birth_place') {
          data[i] = this.userDetailInfo[i][0] + '/' + this.userDetailInfo[i][1];
        } else {
          data[i] = this.userDetailInfo[i]
        }
      }
      console.log('users data', data);
      axios.put(BackURL + 'users', {
        info: data
      }).then((res) => {
        console.log(res);
        // this.userDetailInfo.owner_id = res.data.data;
        console.log('updateInfo', this.screeningList);
        this.modal1 = false;
        this.$Message.info({
          content: '保存成功'
        })
        window.sessionStorage.setItem('screeningList', JSON.stringify(this.screeningList));
      }).catch((err) => {
        console.log(err)
      })
    },
    getMedicalNum(num, index) {
      // console.log('num1', num)
      // console.log('index', index)
      this.oldMedicalNum = num;
    },
    updateMedicalNum(num, id) {
      if (this.oldMedicalNum != num) {
        axios.post(BackURL + 'medicalNum', {
          medicalNum: num,
          imageId: id
        }).then((res) => {
          console.log('updateMedicalNum', this.screeningList);
          window.sessionStorage.setItem('screeningList', JSON.stringify(this.screeningList));
        }).catch((err) => {

        })
      }
    },
    _initScroll() {
      this.screening_scroll = new BScroll(this.$refs.screening_container, {
        probeType: 3, //实时监控滑动距离
        mouseWheel: true, //鼠标滑动
        momentumLimitDistance: 0,
        bounce: false, //禁止回弹
        scrollbar: {
          fade: false, //显示滚动条
          interactive: true //按住滑动条实现滑动
        }
      })
      // this.screening_scroll.on('scroll', (pos) => {
      //     this.scrollY = Math.abs(Math.round(pos.y))
      //     var num = (this.scrollY - 35) / 85;
      //     this.detailInfo = this.screeningList[parseInt(num)];
      // })
    },
    changeMode(obj) {
      console.log('changeMode', obj);
      obj.mode = obj.mode ? 0 : 1;
    },
    showImage(url) {
      this.visible = !this.visible;
      this.showImgUrl = url;
    },
    test() {
      console.log('testtesttesttesttesttesttest')
      // alert('finished')
      this.screeningList = JSON.parse(window.sessionStorage.getItem('screeningList'));
      // vm.$forceUpdate();
      // location.reload()
      console.log(this)
      this.updateList = false
    },
    start(item) {
      var _that = this;
      this.underScreeningList = parseInt(window.localStorage.getItem('underScreeningList'));
      if (this.underScreeningList == 1) {
        return;
      } else {
        // console.log('screening', item);
        this.underScreeningList = 1;
        window.localStorage.setItem('underScreeningList', this.underScreeningList);
        // if (item.identify_num == null) {
        //     this.$Message.info({content: '请完善基本信息', duration: 1.5})
        //     // this.$Notice.warning({title: '请完善基本信息'});
        //     return;
        // }
        console.log('start screnning', item)
        item.status = 2;
        window.sessionStorage.setItem('screeningList', JSON.stringify(this.screeningList));
        axios.post(BackURL + 'screening2', {
          image_id: item.image_id,
          owner_id: item.owner_id,
          image_url: item.image,
          status: item.status,
          type: item.mode,
          medical_num: item.medical_num
        }).then((res) => {
          console.log('screening new', res);
          if (res.data.status == 2) {
            console.log('finishedfinishedfinishedfinished                ')
            console.log('finished item', item)
            // vm.$forceUpdate();
            item.status = 1;
            this.underScreeningList = 0;
            window.localStorage.setItem('underScreeningList', this.underScreeningList);
            if (this.auto_screen) {
              this.finishScreeningList++;
            }
            console.log('leave page 255555555555')
            var len = this.waitingScreeningList.length;
            for (var i = 0; i < len; i++) {
              if (this.waitingScreeningList[i].id == item.id) {
                this.waitingScreeningList.splice(i, 1);
                window.localStorage.setItem('waitingScreeningList', JSON.stringify(this.waitingScreeningList))
                // console.log('this.waitingScreeningList.splice', this.waitingScreeningList);
                // console.log('this.waitingScreeningList.splice', this.waitingScreeningList.length);
                break;
              }
            }
            console.log('first screeningList', this.screeningList)
            window.sessionStorage.setItem('screeningList', JSON.stringify(this.screeningList));
            console.log('强制刷新')
            this.screeningList = JSON.parse(window.sessionStorage.getItem('screeningList'));
            console.log('second screeningList', this.screeningList)
            // vm.$set(this.screeningList,JSON.parse(window.sessionStorage.getItem('screeningList')))
            // this.nextTick(() => {
            //     console.log('force 更新')
            // this.$forceUpdate();
            // })
            console.log('强制刷新完成')
            // _that.updateList = false
            // this.test()
          } else {
            console.log('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
            item.status = 0;
            window.sessionStorage.setItem('screeningList', JSON.stringify(this.screeningList));
            this.underScreeningList = 0;
            window.localStorage.setItem('underScreeningList', this.underScreeningList);
          }
        }).catch((err) => {
          // console.log('screening err', err);
          console.log('yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy')
          item.status = 0;
          window.sessionStorage.setItem('screeningList', JSON.stringify(this.screeningList));
          this.underScreeningList = 0;
          window.localStorage.setItem('underScreeningList', this.underScreeningList);
        })
      }
    },
    getDetail(item) {
      console.log('getDetail', item);
      window.open(FrontURL + '#/detail2/' + item.medical_num);
    },
    showDetail(obj) {
      // console.log(obj)
      this.detailInfo = obj;
    },
    autoScreen() {
      //使用localStorage
      if (this.auto_screen) {
        // console.log(this.auto_screen);
        if (this.waitingScreeningList.length) {
          this.screeningList.forEach((item, index) => {
            if (item.id == this.waitingScreeningList[0].id) {
              // console.log(item, index);
              this.start(this.screeningList[index]);
            }
          })
        }
      }
      window.localStorage.setItem('auto_screen', this.auto_screen)
    },
    compare(obj1, obj2) {
      var val1 = obj1.medical_num;
      var val2 = obj2.medical_num;
      if (val1 < val2) {
        return 1;
      } else if (val1 > val2) {
        return -1;
      } else {
        return 0
      }
    },
    addList(arg) {
      // var oldLength = this.screeningList.length;
      axios.get(BackURL + 'image2').then((res) => {
        // console.log('images', res);
        var len = res.data.data;
        // console.log('len', len);
        if (Array.isArray(arg)) {
          // console.log('array')
          arg.forEach((value, index) => {
            // console.log('index', index);
            // console.log('arg length', arg.length);
            var length = len - (arg.length - index) + 1;
            // console.log('length', length)
            var data = {
              id: length,
              time: new Date().toLocaleTimeString('chinese', {
                hour12: false
              }),
              name: this.patientInfo.name ? this.patientInfo.name : '未命名' + length,
              image: value.url,
              mode: this.screeningList.length ? (this.screeningList[0].mode == 0 ? 1 : 0) : 0,
              status: 0,
              medical_num: value.medicalNum,
              image_id: value.id,
              gender: this.patientInfo.gender ? this.patientInfo.gender : '',
              identify_num: this.patientInfo.identify_num ? this.patientInfo.identify_num : null,
              birth_date: '',
              telephone: null,
              birth_place: this.patientInfo.birth_place ? this.patientInfo.birth_place : [],
              medical_history: ''
            }

            var newData = {};
            for (var i in data) {
              if (i == 'birth_place') {
                if (data[i]) {
                  newData[i] = data[i][0] + '/' + data[i][1];
                } else {
                  newData[i] = '';
                }
              } else {
                newData[i] = data[i];
              }
            }
            axios.post(BackURL + 'users', {
              info: newData
            }).then((res) => {
              // console.log('users result', res);
              data.owner_id = res.data.data;
              this.screeningList = this.screeningList ? this.screeningList : [];
              this.screeningList.unshift(data);
              this.waitingScreeningList.push(data);
              window.localStorage.setItem('waitingScreeningList', JSON.stringify(this.waitingScreeningList))
              var obj = JSON.stringify(this.screeningList)
              window.sessionStorage.setItem('screeningList', obj)
              window.sessionStorage.setItem('screeningNum', window.localStorage.getItem('screeningNum') ? parseInt(window.localStorage.getItem('screeningNum')) + 1 : 1)
              axios.post(BackURL + 'tasks', {
                image_id: newData.image_id,
                owner_id: res.data.data,
              }).then((res) => {
                this.underScreeningList = parseInt(window.localStorage.getItem('underScreeningList'));
                if (this.underScreeningList == 0 && this.auto_screen) {
                  this.finishScreeningList++;
                }
                // console.log('tasks', res);
              }).catch((err) => {

              })
            }).catch((err) => {
              console.log(err);
            })
          })
        } else {
          // console.log('normal')
          var data = {
            id: len,
            time: new Date().toLocaleTimeString('chinese', {
              hour12: false
            }),
            name: this.patientInfo.name ? this.patientInfo.name : '未命名' + len,
            image: arg.url,
            mode: this.screeningList.length ? (this.screeningList[0].mode == 0 ? 1 : 0) : 0,
            status: 0,
            medical_num: arg.medicalNum,
            image_id: arg.id,
            gender: this.patientInfo.gender ? this.patientInfo.gender : '',
            identify_num: this.patientInfo.identify_num ? this.patientInfo.identify_num : null,
            birth_date: '',
            telephone: null,
            birth_place: this.patientInfo.birth_place ? this.patientInfo.birth_place : [],
            medical_history: ''
          }

          var newData = {};
          for (var i in data) {
            if (i == 'birth_place') {
              if (data[i].length) {
                newData[i] = data[i][0] + '/' + data[i][1];
              } else {
                newData[i] = '';
              }
            } else {
              newData[i] = data[i];
            }
          }
            axios.post(BackURL + 'users', {
            info: newData
          }).then((res) => {
            // console.log('users result', res);
            data.owner_id = res.data.data;
            this.screeningList = this.screeningList ? this.screeningList : [];
            this.screeningList.unshift(data);
            // console.log('this,screeningList new', this.screeningList)
            this.waitingScreeningList.push(data);
            window.localStorage.setItem('waitingScreeningList', JSON.stringify(this.waitingScreeningList))
            var obj = JSON.stringify(this.screeningList)
            window.sessionStorage.setItem('screeningList', obj)
            window.sessionStorage.setItem('screeningNum', window.localStorage.getItem('screeningNum') ? parseInt(window.localStorage.getItem('screeningNum')) + 1 : 1)
            axios.post(BackURL + 'tasks', {
              image_id: newData.image_id,
              owner_id: res.data.data,
            }).then((res) => {
              this.underScreeningList = parseInt(window.localStorage.getItem('underScreeningList'));
              if (this.underScreeningList == 0 && this.auto_screen) {
                this.finishScreeningList++;
              }
            }).catch((err) => {

            })
          }).catch((err) => {
            console.log(err);
          })
        }
      }).catch((err) => {
        console.log('images', err);
      })
    },
    onFileChange(e) {
      var filearr = [];
      var files = e.target.files;
      for (var i = 0; i < files.length; i++) {
        filearr.push(files[i]);
      }
      var formData = new FormData();
      for (var i = 0; i < filearr.length; i++) {
        // console.log('filearr[i]', filearr[i]);
        formData.append("file", filearr[i]);
      }

      var config = {
        headers: {
          'Content-Type': 'multipart/form-data',
          "token": window.localStorage.getItem('screeningLogin')
        }
      }

      console.log('formData', formData.getAll('file'));
      axios.post(BackURL + 'upload', formData, config).then((res) => {
        // this.addList(res.data)
        console.log(res.data)
        if (Array.isArray(res.data)) {
          var data = res.data.sort(this.compare)
          this.addList(data);
        } else {
          this.addList(res.data);
        }
        // console.log(data)
      }).catch((err) => {
        console.log(err)
      })
    },
    deepCopy(data) {
      var arr = new Array();
      var len = data.length;
      for (var i = 0; i < len; i++) {
        var obj = {};
        for (var j in data[i]) {
          // console.log('j222222', j)
          obj[j] = data[i][j];
        }
        arr.push(obj);
      }
      return arr;
    }
  },
  watch: {
    screeningList: function() {
      console.log('this.screeningList 66666', this.screeningList);
      if (this.screeningList.length) {
        // console.log(1111111111)
        this.detailInfo = this.screeningList[0];
        this.$nextTick(() => {
          this._initScroll();
        })
      }
    },
    waitingScreeningList: function() {
      // console.log(this.auto_screen);
      // console.log(typeof(this.auto_screen));
      // if (this.auto_screen) {
      //     console.log('auto screening')
      //     if (this.waitingScreeningList.length) {
      //         this.screeningList.forEach((item, index) => {
      //             if (item.id == this.waitingScreeningList[0].id) {
      //                 console.log(item, index);
      //                 this.start(this.screeningList[index]);
      //             }
      //         })
      //     }
      // }
    },
    finishScreeningList: function() {
      console.log('finishScreeningList ++++++++++++++++++++++++++++++++')
      if (this.auto_screen) {
        // console.log('auto screening')
        if (this.waitingScreeningList.length) {
          this.screeningList.forEach((item, index) => {
            if (item.id == this.waitingScreeningList[0].id) {
              console.log(item, index);
              this.start(this.screeningList[index]);
            }
          })
        }
      }
    }
  },
  mounted() {
    var _that = this;
    window.onresize = function() {
      _that.clientHeight = document.documentElement.clientHeight - 355;
      _that.clientWidth = document.documentElement.clientWidth - 100;
      // alert('window of size change')
      // _that.refreshComponent = false;
      // _that.$nextTick(() => {
      //     _that.refreshComponent = true;
      // })
      // console.log('this.clientHeight', this.clientHeight)
      // console.log('this.clientWidth', this.clientWidth)
    }

    this.$watch('userDetailInfo.identify_num', this.debounce((newQuery) => {
      this.$emit('userDetailInfo.identify_num', newQuery)
      console.log('this.userDetailInfo.identify_num', this.userDetailInfo.identify_num)
      if (this.userDetailInfo.identify_num) {
        axios.get(BackURL + 'users', {
          params: {
            identify_num: this.userDetailInfo.identify_num
          }
        }).then((res) => {
          console.log('users res', res.data.data)
          if (res.data.data) {
            // this.userDetailInfo.name = res.data.data.name;
            // this.userDetailInfo.gender = res.data.data.gender;
            // this.userDetailInfo.birth_date = res.data.data.birth_date;
            // this.userDetailInfo.telephone = res.data.data.phone;
            // this.userDetailInfo.medical_history = res.data.data.medical_history;
            this.userDetailInfo.birth_place = res.data.data.birth_place.split('/')
          }
        }).catch((err) => {
          console.log('users err', err)
        })
      }
    }, 500))

    // console.log('screening mounted');
    this.clientHeight = document.documentElement.clientHeight - 355;
    this.clientWidth = document.documentElement.clientWidth - 100;
    //使用localStorage
    this.auto_screen = window.localStorage.getItem('auto_screen') ? JSON.parse(window.localStorage.getItem('auto_screen')) : false;
    this.waitingScreeningList = JSON.parse(window.localStorage.getItem('waitingScreeningList')) ? JSON.parse(window.localStorage.getItem('waitingScreeningList')) : [];
    // console.log('this.waitingScreeningList.length', this.waitingScreeningList.length);
    // console.log('this.auto_screen', this.auto_screen)
    if (this.auto_screen && this.waitingScreeningList.length) {
      // console.log('this.waitingScreeningList', this.waitingScreeningList);
      this.screeningList.forEach((item, index) => {
        if (item.id == this.waitingScreeningList[0].id) {
          // console.log(item, index);
          this.start(this.screeningList[index]);
        }
      })
    }
    // console.log('this.screeningList.length', this.screeningList.length)
    if (this.screeningList.length) {
      // console.log('_initScroll')
      this.$nextTick(() => {
        this._initScroll();
      })
      this.detailInfo = this.screeningList[0];
    }

    var cityArr = [];
    cityArr[0] = ['北京市', '东城区', '西城区', '崇文区', '宣武区', '朝阳区', '丰台区', '石景山区', '海淀区', '门头沟区', '房山区', '通州区', '顺义区', '昌平区', '大兴区', '怀柔区', '平谷区', '密云县', '延庆县'];
    cityArr[1] = ['天津市', '和平区', '河东区', '河西区', '南开区', '河北区', '红桥区', '塘沽区', '汉沽区', '大港区', '东丽区', '西青区', '津南区', '北辰区', '武清区', '宝坻区', '宁河县', '静海县', '蓟县'];
    cityArr[2] = ['上海市', '黄浦区', '卢湾区', '徐汇区', '长宁区', '静安区', '普陀区', '闸北区', '虹口区', '杨浦区', '闵行区', '宝山区', '嘉定区', '浦东新区', '金山区', '松江区', '青浦区', '南汇区', '奉贤区', '崇明县'];
    cityArr[3] = ['重庆市', '万州区', '涪陵区', '渝中区', '大渡口区', '江北区', '沙坪坝区', '九龙坡区', '南岸区', '北碚区', '万盛区', '双桥区', '渝北区', '巴南区', '黔江区', '长寿区', '江津区', '合川区', '永川区', '南川区', '綦江县', '潼南县', '铜梁县', '大足县', '荣昌县', '璧山县', '梁平县', '城口县', '丰都县', '垫江县', '武隆县', '忠县', '开县',
      '云阳县', '奉节县', '巫山县', '巫溪县', '石柱土家族自治县', '秀山土家族苗族自治县', '酉阳土家族苗族自治县', '彭水苗族土家族自治县'
    ];
    cityArr[4] = ['河北省', '石家庄市', '唐山市', '秦皇岛市', '邯郸市', '邢台市', '保定市', '张家口市', '承德市', '沧州市', '廊坊市', '衡水市'];
    cityArr[5] = ['河南省', '郑州市', '开封市', '洛阳市', '平顶山市', '安阳市', '鹤壁市', '新乡市', '焦作市', '济源市', '濮阳市', '许昌市', '漯河市', '三门峡市', '南阳市', '商丘市', '信阳市', '周口市', '驻马店市'];
    cityArr[6] = ['云南省', '昆明市', ' 曲靖市', '玉溪市', '保山市', '昭通市', '丽江市', '思茅市', '临沧市', '楚雄彝族自治州', '红河哈尼族彝族自治州', '文山壮族苗族自治州', '西双版纳傣族自治州', '大理白族自治州', '德宏傣族景颇族自治州', '怒江傈僳族自治州', '迪庆藏族自治州'];
    cityArr[7] = ['辽宁省', '沈阳市', '大连市', '鞍山市', '抚顺市', '本溪市', '丹东市', '锦州市', '营口市', '阜新市', '辽阳市', '盘锦市', '铁岭市', '朝阳市', '葫芦岛市'];
    cityArr[8] = ['黑龙江省', '哈尔滨市', '齐齐哈尔市', '鸡西市', '鹤岗市', '双鸭山市', '大庆市', '伊春市', '佳木斯市', '七台河市', '牡丹江市', '黑河市', '绥化市', '大兴安岭地区'];
    cityArr[9] = ['湖南省', '长沙市', '株洲市', '湘潭市', '衡阳市', '邵阳市', '岳阳市', '常德市', '张家界市', '益阳市', '郴州市', '永州市', '怀化市', '娄底市', '湘西土家族苗族自治州'];
    cityArr[10] = ['安徽省', '合肥市', '芜湖市', '蚌埠市', '淮南市', '马鞍山市', '淮北市', '铜陵市', '安庆市', '黄山市', '滁州市', '阜阳市', '宿州市', '巢湖市', '六安市', '亳州市', '池州', '宣城市'];
    cityArr[11] = ['山东省', '济南市', '青岛市', '淄博市', '枣庄市', '东营市', '烟台市', '潍坊市', '济宁市', '泰安市', '威海市', '日照市', '莱芜市', '临沂市', '德州市', '聊城市', '滨州市', '菏泽市'];
    cityArr[12] = ['新疆维吾尔自治区', '乌鲁木齐市', '克拉玛依市', '吐鲁番地区', '哈密地区', '昌吉回族自治州 ', '博尔塔拉蒙古自治州 ', '巴音郭楞蒙古自治州 ', '阿克苏地区', '克孜勒苏柯尔克孜自治州 ', '喀什地区', '和田地区', '伊犁哈萨克自治州', '塔城地区', '阿勒泰地区', '石河子市', '阿拉尔市', '图木舒克市', '五家渠市'];
    cityArr[13] = ['江苏省', '南京市', '无锡市', '徐州市', '常州市', '苏州市', '南通市', '连云港市', '淮安市', '盐城市', '扬州市', '镇江市', '泰州市', '宿迁市'];
    cityArr[14] = ['浙江省', '杭州市', '宁波市', '温州市', '嘉兴市', '湖州市', '绍兴市', '金华市', '衢州市', '舟山市', '台州市', '丽水市'];
    cityArr[15] = ['江西省', '南昌市', '景德镇市', '萍乡市', '九江市', '新余市', '鹰潭市', '赣州市', '吉安市', '宜春市', '抚州市', '上饶市'];
    cityArr[16] = ['湖北省', '武汉市', '黄石市', '十堰市', '宜昌市', '襄樊市', '鄂州市', '荆门市', '孝感市', '荆州市', '黄冈市', '咸宁市', '随州市', '恩施土家族苗族自治州', '仙桃市', '潜江市', '天门市', '神农架林区'];
    cityArr[17] = ['广西壮族', '南宁市', '柳州市', '桂林市', '梧州市', '北海市', '防城港市', '钦州市', '贵港市', '玉林市', '百色市', '贺州市', '河池市', '来宾市', '崇左市'];
    cityArr[18] = ['甘肃省', '兰州市', '嘉峪关市', '金昌市', '白银市', '天水市', '武威市', '张掖市', '平凉市', '酒泉市', '庆阳市', '定西市', '陇南市', '临夏回族自治州', '甘南藏族自治州'];
    cityArr[19] = ['山西省', '太原市', '大同市', '阳泉市', '长治市', '晋城市', '朔州市', '晋中市', '运城市', '忻州市', '临汾市', '吕梁市'];
    cityArr[20] = ['内蒙古自治区', '呼和浩特市', '包头市', '乌海市', '赤峰市', '通辽市', '鄂尔多斯市', '呼伦贝尔市', '巴彦淖尔市', '乌兰察布市', '兴安盟', '锡林郭勒盟', '阿拉善盟'];
    cityArr[21] = ['陕西省', '西安市', '铜川市', '宝鸡市', '咸阳市', '渭南市', '延安市', '汉中市', '榆林市', '安康市', '商洛市'];
    cityArr[22] = ['吉林省', '长春市', '吉林市', '四平市', '辽源市', '通化市', '白山市', '松原市', '白城市', '延边朝鲜族自治州'];
    cityArr[23] = ['福建省', '福州市', '厦门市', '莆田市', '三明市', '泉州市', '漳州市', '南平市', '龙岩市', '宁德市'];
    cityArr[24] = ['贵州省', '贵阳市', '六盘水市', '遵义市', '安顺市', '铜仁地区', '黔西南布依族苗族自治州', '毕节地区', '黔东南苗族侗族自治州', '黔南布依族苗族自治州'];
    cityArr[25] = ['广东省', '广州市', '韶关市', '深圳市', '珠海市', '汕头市', '佛山市', '江门市', '湛江市', '茂名市', '肇庆市', '惠州市', '梅州市', '汕尾市', '河源市', '阳江市', '清远市', '东莞市', '中山市', '潮州市', '揭阳市', '云浮市'];
    cityArr[26] = ['青海省', '西宁市', '海东地区', '海北藏族自治州', '黄南藏族自治州', '海南藏族自治州', '果洛藏族自治州', '玉树藏族自治州', '海西蒙古族藏族自治州'];
    cityArr[27] = ['西藏', '拉萨市', '昌都地区', '山南地区', '日喀则地市', '那曲地区', '阿里地区', '林芝地区'];
    cityArr[28] = ['四川省', '成都市', '自贡市', '攀枝花市', '泸州市', '德阳市', '绵阳市', '广元市', '遂宁市', '内江市', '乐山市', '南充市', '眉山市', '宜宾市', '广安市', '达州市', '雅安市', '巴中市', '资阳市', '阿坝藏族羌族自治州', '甘孜藏族自治州', '凉山彝族自治州'];
    cityArr[29] = ['宁夏回族', '银川市', '石嘴山市', '吴忠市', '固原市', '中卫市'];
    cityArr[30] = ['海南省', '海口市', '三亚市', '五指山市', '琼海市', '儋州市', '文昌市', '万宁市', '东方市', '定安县', '屯昌县', '澄迈县', '临高县', '白沙黎族自治县', '昌江黎族自治县', '乐东黎族自治县', '陵水黎族自治县', '保亭黎族苗族自治县', '琼中黎族苗族自治县'];
    cityArr[31] = ['台湾省', '台北市', '高雄市', '基隆市', '台中市', '台南市', '新竹市', '嘉义市'];
    cityArr[32] = ['香港特别行政区', '中西区', '湾仔区', '东区', '南区', '油尖旺区', '深水埗区', '九龙城区', '黄大仙区', '观塘区', '荃湾区', '葵青区', '沙田区', '西贡区', '大埔区', '北区', '元朗区', '屯门区', '离岛区'];
    cityArr[33] = ['澳门特别行政区', '澳门'];
    var data = new Array();
    for (var i = 0; i < cityArr.length; i++) {
      var temp = {
        "value": '',
        "label": '',
        "children": []
      }
      for (var j = 0; j < cityArr[i].length; j++) {
        if (j == 0) {
          temp.value = cityArr[i][j]
          temp.label = cityArr[i][j]
        } else {
          var obj = {
            "value": cityArr[i][j],
            "label": cityArr[i][j]
          }
          temp.children.push(obj)
        }
      }
      data.push(temp)
    }
    this.nativePlace = data
  },
  created() {
    // console.log('screening created')
    // console.log('ipcRender', ipcRender)
    var _that = this;
    this.screeningList = JSON.parse(window.sessionStorage.getItem('screeningList')) ? JSON.parse(window.sessionStorage.getItem('screeningList')) : [];
    console.log('JSON.PARSE', this.screeningList);
    // _that.screeningList = JSON.parse(window.localStorage.getItem('screeningList'))
    ipcRender.on('upload', function(event, arg) {
      // console.log('3dsdasdadsdsd');
      _that.addList(arg)
    })

    ipcRender.on('patientInfo', (event, arg) => {
      // console.log('patientInfo', arg);
      // this.patientInfo.identify_num = arg.split(' ')[0].split(':')[1];
      // this.patientInfo.name = arg.split(' ')[1].split(':')[1];
      // this.patientInfo.gender = arg.split(' ')[2].split(':')[1];
      // this.patientInfo.birth_place = arg.split(' ')[3].split(':')[1].split('/');
      this.patientInfo.identify_num = arg.identify_num;
      this.patientInfo.name = arg.name;
      this.patientInfo.gender = arg.gender;
      this.patientInfo.birth_place = arg.native_place;
      console.log('this.patientInfo', this.patientInfo);
    })

    // ipcRender.on('getToken', () => {
    ipcRender.send('sendToken', window.localStorage.getItem('screeningLogin'));
    // })


    event.$on('getOriginData', (arg) => {
      console.log('getOriginData', arg);
      axios.get(BackURL + 'screeningList').then((res) => {
        // console.log('screeningList', res);
        res.data.data.forEach((item, index) => {
          // console.log('332323ssss', item)
          // console.log('332323index', index)
          item.birth_place = item.birth_place ? '[]' : item.birth_place.split('/');
        })
        this.screeningList = res.data.data.sort(this.compare);
        window.sessionStorage.setItem('screeningList', JSON.stringify(this.screeningList));
        if (this.screeningList.length) {
          console.log('_initScroll')
          this.$nextTick(() => {
            this._initScroll();
          })
          this.detailInfo = this.screeningList[0];
        }
        this.waitingScreeningList = this.deepCopy(this.screeningList);
        window.localStorage.setItem('waitingScreeningList', JSON.stringify(this.waitingScreeningList))
        console.log('this.waitingScreeningList', this.waitingScreeningList);
        console.log('33223333', this.screeningList);
      }).catch((err) => {
        console.log('screeningList', err);
      })
    })

    event.$on('clearScreening', () => {
      console.log('clearScreening111111', this.screeningList);
      var data = this.deepCopy(this.screeningList);
      var len = 0;
      data.forEach((item, index) => {
        console.log(index)
        console.log(item)
        if (item.status == 1) {
          console.log('ddddddddddddd')
          this.screeningList.splice(index - len, 1);
          len++;
        }
      })
      console.log('clearScreening2222222', this.screeningList);
      window.sessionStorage.setItem('screeningList', JSON.stringify(this.screeningList));
    })
  },
  destroyed() {
    // console.log(event)
    console.log('screening restroyed');
    // ipcRender.removeListener('upload', function () {
    //     console.log('removeListener');
    // });
    ipcRender.removeAllListeners('upload');
    ipcRender.removeAllListeners('patientInfo');
    event.$off('clearScreening');
    event.$off('getOriginData');
  }
}
</script>

<style scoped lang="scss">
.screening2-container {
    font-family: 'Microsoft YaHei';
    font-size: 20px;
    margin: 0 50px;
    background-color: rgba(117, 117, 117, 0.5);
    position: absolute;
    width: 100%;
    top: 350px;
    z-index: -99;
    overflow: hidden;
    .screening2-item {
        display: flex;
        justify-content: space-around;
        font-size: 20px;
        font-family: 'Microsoft YaHei';
        font-weight: bold;
        text-align: center;
        height: 35px;
        line-height: 35px;
        .one {
            flex: 1;
        }
        .two {
            flex: 2;
        }
    }
    .screening2-list {
        &:last-child {
            .right {
                border-bottom: none;
            }
        }
        display: flex;
        justify-content: space-around;
        align-items: center;
        .left {
            flex: 1;
            height: 75px;
            line-height: 75px;
            text-align: center;
            /*background-color: rgb(245, 245, 245);*/
            box-shadow: 5px 5px 5px rgba(207, 207, 207, 0.5);
            background: linear-gradient(rgb(255, 255, 255), rgb(212, 212, 212));
            margin-top: -10px;
            margin-left: -20px;
            span {
                &:first-child {
                    color: rgb(169, 72, 102);
                }
                &:last-child {
                    font-size: 16px;
                }
            }
        }
        .right {
            flex: 8;
            display: flex;
            justify-content: space-around;
            align-items: center;
            height: 85px;
            background-color: rgb(245, 245, 245);
            margin-left: 5px;
            border-bottom: 1px solid rgb(208, 208, 208);
            .update-info {
                cursor: pointer;
            }
            .one {
                flex: 1;
            }
            .change-mode:hover {
                cursor: pointer;
            }
            .two {
                flex: 2;
                .start-red {
                    color: rgb(169, 72, 102);
                }
                em {
                    font-style: normal;
                    /*&:nth-child(-n+2) {*/
                    /*color: rgb(169, 72, 102);*/
                    /*}*/
                    &:last-child {
                        color: rgb(175, 174, 174);
                    }
                }
                em:hover {
                    text-decoration: underline;
                    cursor: pointer;
                }
                input {
                    background-color: rgb(182, 182, 182);
                    border: none;
                    padding: 0 5px;
                    border-radius: 4px;
                    font-size: 16px;
                }
                input::-webkit-inner-spin-button,
                input::-webkit-outer-spin-button {
                    -webkit-appearance: none;
                }
                input[type='number'] {
                    -moz-appearance: textfield;
                }
            }
            .start {
                color: rgb(234, 0, 64);
            }
            .finish {
                color: rgb(79, 199, 130);
            }
            .screening {
                color: rgb(213, 168, 0);
            }
            span {
                display: inline-block;
                text-align: center;
                margin-left: 15px;
            }
            img {
                width: 60px;
                border-radius: 5px;
            }
        }
    }
}

.screening2-listdetail {
    height: 190px;
    background-color: rgb(182, 182, 182);
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin-bottom: 5px;
    position: fixed;
    width: 100%;
    top: 159px;
    div {
        background-color: rgb(245, 245, 245);
        height: 160px;
        font-size: 20px;
        font-family: 'Microsoft YaHei';
        max-width: 20%;
        /*min-width: 10%;*/
        img {
            /*width: 130px;*/
            height: 130px;
            -webkit-border-radius: 5px;
            -moz-border-radius: 5px;
            border-radius: 5px;
        }
    }
    .one {
        display: flex;
        align-items: center;
        padding: 0 20px;
        box-shadow: 5px 5px 5px rgba(207, 207, 207, 0.5);
        background: linear-gradient(rgb(255, 255, 255), rgb(212, 212, 212));
        span {
            &:first-child {
                color: rgb(169, 72, 102);
            }
            &:last-child {
                font-size: 16px;
                margin-left: 5px;
            }
        }
    }
    .two {
        background: none;
        text-align: center;
        min-width: 10%;
        /*display: flex;*/
        /*align-items: center;*/
        p {
            text-align: center;
        }
    }
    .three {
        padding: 10px 20px;
        width: 18%;
        box-shadow: 5px 5px 5px rgba(207, 207, 207, 0.5);
        background: linear-gradient(rgb(255, 255, 255), rgb(212, 212, 212));
        span {
            display: block;
            em {
                font-style: normal;
            }
        }
        .detail,
        .start {
            color: rgb(169, 72, 102);
        }
        .result {
            @extend .start;
            font-weight: bold;
        }
        .start:hover {
            cursor: pointer;
            text-decoration: underline;
        }
        .detail:hover {
            cursor: pointer;
            text-decoration: underline;
        }
        .delete:hover {
            cursor: pointer;
            text-decoration: underline;
        }
        .delete {
            color: rgb(175, 174, 174);
        }
    }
}

.screening2-autoupload {
    height: 34px;
    position: absolute;
    top: 125px;
    text-align: right;
    width: 100%;
    font-family: 'Microsoft YaHei';
    font-size: 16px;
    .image-upload {
        position: relative;
        margin-right: 20px;
        span {
            display: inline-block;
            height: 30px;
            line-height: 30px;
            width: 100%;
            padding: 0 20px;
        }
        input {
            position: absolute;
            top: 0;
            left: 0;
            opacity: 0;
            width: 100%;
            height: 30px;
            /*padding: 0 10px;*/
        }
    }
    .auto-screen {
        margin-right: 20px;
    }
}

.screening2-info {
    p {
        /*margin: 20px 0;*/
        display: flex;
        justify-content: space-between;
        margin: 0 15px 15px;
        font-size: 18px;
        span {
            display: inline-block;
            width: 45%;
            em {
                font-style: normal;
                color: rgb(234, 0, 64);
                font-size: 18px;
            }
            input {
                height: 30px;
                line-height: 30px;
                padding: 0 5px;
                border-radius: 4px;
                border: 1px solid #dcdee2;
                display: block;
                width: 100%;
            }
            input::-webkit-inner-spin-button,
            input::-webkit-outer-spin-button {
                -webkit-appearance: none;
            }
            input[type="number"] {
                -moz-appearance: textfield;
            }
        }
        &:last-child {
            display: block;
            span {
                width: 100%;
                input {
                    width: 100%;
                }
            }
        }
    }
}
</style>
